<?php
namespace app\home\controller;

use think\Request;
use nekoing\BaseController;

class Util extends BaseController
{
    private $author = 'Nekoing';
    
    public function model()
    {
        $models = $this->models();
        foreach ($models as $model) {
            echo '注入中...' . get_class($model['class']) . '<br/>';
            $this->injectionAttr($model['path'], $model['columns']);
        }
        echo '完成...';
    }
    
    public function debug()
    {
        $input = input();
        $this->json($input);
    }
    
    private function models()
    {
        $modelPath = __DIR__ . '/../model';
        $models = [];
        $dir = dir($modelPath);
        $db = \think\Db::connect();
        while (@$f = $dir->read()) {
            $file = $modelPath . '/' . $f;
            if(is_file($file)) {
                $className = '\\app\\' . Request::instance()->module() . '\\model\\' . str_replace('.php', '', $f);
                $class = new $className();
                
                $attributes = [];
                $table = $class->db()->getTable();

                $sql = "select COLUMN_NAME as name, DATA_TYPE as type from information_schema.COLUMNS where table_name = '$table'";
                $columns = $db->query($sql);

                $models[] = [
                    'path' => $file,
                    'class' => $class,
                    'columns' => $columns
                ];
            }
        }
        return $models;
    }
    
    private function injectionAttr($file, $columns)
    {
        $inject = "/**\r\n * @author {$this->author}\r\n *\r\n";
        foreach ($columns as $row) {
            $name = $row['name'];
            $type = $this->formatType($row['type']);
            $inject .= " * @property {$type} {$row['name']}\r\n";
        }
        $inject .= " */\r\n";
        
        $content = file_get_contents($file);
        
        $content = preg_replace('/\/\*\*.*?\*\/\s*\r?\n/s', '', $content);
        $content = preg_replace('/class +\w+/', $inject . '$0', $content);
        file_put_contents($file, $content);
    }
    
    private function formatType($type)
    {
        if(in_array($type, ['tinyint', 'smallint', 'mediumint', 'int', 'integer', 'bigint'])) {
            return 'integer';
        }
        if(in_array($type, ['double', 'float', 'decimal', 'numeric'])) {
            return 'float';
        }
        return 'string';
    }
}

?>